// Bristleback plugin - Copyright (c) 2010 bristleback.googlecode.com
// ---------------------------------------------------------------------------
// This program is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published by the
// Free Software Foundation; either version 3 of the License, or (at your
// option) any later version.
// This library is distributed in the hope that it will be useful,
// but without any warranty; without even the implied warranty of merchantability
// or fitness for a particular purpose.
// You should have received a copy of the GNU Lesser General Public License along
// with this program; if not, see <http://www.gnu.org/licenses/lgpl.html>.
// ---------------------------------------------------------------------------
package pl.bristleback.server.bristle.states;

import org.apache.log4j.Logger;
import pl.bristleback.server.bristle.config.BristleConstants;
import pl.bristleback.server.bristle.config.ClassConfiguration;
import pl.bristleback.server.bristle.config.ClassConfigurationUtil;

import java.util.List;
import java.util.Map;

/**
 * Server state inspector monitors server and runs listeners defined by user in configuration file.
 * Check {@link pl.bristleback.server.bristle.config.BristleConstants} for the plugin property names of server state listeners.
 * As current version, server start and stop are monitored.
 * These can be used for example to load and save the world of game.
 * <p/>
 * Created on: 2010-10-14 18:17:07 <br/>
 *
 * @author Wojciech Niemiec
 */
public final class ServerStateInspector {
  private static Logger log = Logger.getLogger(ServerStateInspector.class.getName());

  private ServerStateListenerChain serverStateListenerChain;

  /**
   * Instantiates listeners using plugin settings.
   *
   * @param pluginSettings plugin settings.
   */
  public void loadServerStateListeners(Map<String, Object> pluginSettings) {
    serverStateListenerChain = new ServerStateListenerChain();
    List<ClassConfiguration> listenerClasses = getServerStateListenerClasses(pluginSettings);
    for (ClassConfiguration classConfiguration : listenerClasses) {
      serverStateListenerChain.addListener(
        ClassConfigurationUtil.getInstanceFromConfiguration(ServerStateListener.class, classConfiguration));
    }
  }

  private List<ClassConfiguration> getServerStateListenerClasses(Map<String, Object> pluginSettings) {
    return ClassConfigurationUtil
      .getClassConfigurationsFromSettingsMap(BristleConstants.SERVER_STATE_LISTENER_SETTING_KEY_PREFIX, pluginSettings);
  }

  /**
   * Method invoked by plugin at server start.
   */
  public void serverStart() {
    serverStateListenerChain.serverStart();
  }

  /**
   * Method invoked by plugin at server shutdown.
   */
  public void serverShutdown() {
    serverStateListenerChain.serverShutdown();
  }
}
